<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="./lib/bootstrap.css">
</head>

<body>
    <form id="info">
        <input type="file" name="myfile" id="myfile">
        <input type="button" value="提交" id="btn">
    </form>
    <div>
        <img src="" id="test">
    </div>
    <div class="progress" style="width: 500px; margin: 15px 10px;">
        <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
            0%
        </div>
    </div>
    <script>
        var btn = document.getElementById('btn')
        btn.onclick = function() {
            // var file = document.getElementById('myfile').files[0]
            // if (!file) {
            //     alert('请选择文件')
            // }
            var form = document.getElementById('info')
            var fd = new FormData(form);
            // fd.append('avatar', file)
            var xhr = new XMLHttpRequest();
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var num = Math.ceil((e.loaded / e.total) * 100)
                    var p = document.getElementById('percent')
                    p.style = 'width:' + num + '%'
                    p.innerHTML = num + '%'
                }
            }
            xhr.upload.onload = function(e) {
                var p = document.getElementById('percent')
                p.classList.remove('progress-bar-striped', 'active')
                p.classList.add('progress-bar-success')
            }
            xhr.open('post', 'http://www.liulongbin.top:3006/api/upload/avatar')

            xhr.send(fd)
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var ret = xhr.responseText
                    ret = JSON.parse(ret)
                    var img = document.getElementById('test')
                    img.setAttribute('src', 'http://www.liulongbin.top:3006' + ret.url)
                }
            }
        }
    </script>
</body>

</html>